package com.xr.sunnyday.controller;

import com.xr.sunnyday.entity.Result;
import com.xr.sunnyday.exception.AssociationException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 * @RestControllerAdvice ：将标有@RestController的类进行"duan duan duan"增强
 */
@RestControllerAdvice
public class HandlerAdvice {
    /**
     * @ExceptionHandler: 异常捕手，捕谁要写清楚，
     * 进了方法就相当于进了catch(SunnydayException){
     *     ...我们要捕获后进行的操作
     * }
     * return:要处理的对象
     */
    @ExceptionHandler(AssociationException.class)
    public Result handSunnydayException(AssociationException se){
        return new Result(false,se.getMessage());
    }

    /*@ExceptionHandler(Exception.class)
    public Result handException(Exception e){
        return new Result(false,"发生未知错误，请联系管理员!");
    }*/

    /**
     * 密码错误
     */
    @ExceptionHandler(BadCredentialsException.class)
    public Result handBadCredentialsException(BadCredentialsException he){
        return handleUserPassword();
    }

    /**
     * 用户名不存在
     */
    @ExceptionHandler(InternalAuthenticationServiceException.class)
    public Result handInternalAuthenticationServiceException(InternalAuthenticationServiceException he){
        return handleUserPassword();
    }

    /**
     * 用户名或密码错误
     */
    private Result handleUserPassword(){
        return new Result(false, "用户名或密码错误");
    }
    /**
     * 权限不足
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result handAccessDeniedException(AccessDeniedException he){
        return new Result(false, "没有权限");
    }

}
